package com.haohan.cloud.scm.goods.utils;

import cn.hutool.core.util.StrUtil;
import com.haohan.cloud.scm.api.constant.ScmCacheNameConstant;
import com.haohan.cloud.scm.api.crm.feign.SalesOrderDetailFeignService;
import com.haohan.cloud.scm.api.crm.req.SalesOrderDetailReq;
import com.haohan.cloud.scm.api.manage.dto.PhotoGroupDTO;
import com.haohan.cloud.scm.api.manage.dto.ShopExtDTO;
import com.haohan.cloud.scm.api.manage.entity.Merchant;
import com.haohan.cloud.scm.api.manage.entity.PhotoGallery;
import com.haohan.cloud.scm.api.manage.entity.PhotoGroupManage;
import com.haohan.cloud.scm.api.manage.entity.Shop;
import com.haohan.cloud.scm.api.manage.feign.MerchantFeignService;
import com.haohan.cloud.scm.api.manage.feign.PhotoGroupManageFeignService;
import com.haohan.cloud.scm.api.manage.feign.ShopFeignService;
import com.haohan.cloud.scm.api.saleb.entity.Buyer;
import com.haohan.cloud.scm.api.saleb.feign.BuyOrderDetailFeignService;
import com.haohan.cloud.scm.api.saleb.feign.BuyerFeignService;
import com.haohan.cloud.scm.api.saleb.req.BuyOrderDetailReq;
import com.haohan.cloud.scm.api.salec.feign.StoreProductFeignService;
import com.haohan.cloud.scm.api.salec.req.StoreProductFeignReq;
import com.haohan.cloud.scm.api.supply.feign.SupplierGoodsFeignService;
import com.haohan.cloud.scm.api.supply.feign.SupplyOrderDetailFeignService;
import com.haohan.cloud.scm.api.supply.req.SupplierGoodsReq;
import com.haohan.cloud.scm.api.supply.req.SupplyOrderDetailReq;
import com.haohan.cloud.scm.common.tools.exception.EmptyDataException;
import com.haohan.cloud.scm.common.tools.exception.ErrorDataException;
import com.haohan.cloud.scm.common.tools.util.RUtil;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import com.pig4cloud.pigx.common.core.util.R;
import lombok.AllArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author dy
 * @date 2019/9/14
 */
@Component
@AllArgsConstructor
public class ScmGoodsUtils {

    private final SupplierGoodsFeignService supplierGoodsFeignService;
    private final StoreProductFeignService storeProductFeignService;
    private final MerchantFeignService merchantFeignService;
    private final ShopFeignService shopFeignService;
    private final PhotoGroupManageFeignService photoGroupManageFeignService;
    private final BuyOrderDetailFeignService buyOrderDetailFeignService;
    private final SupplyOrderDetailFeignService supplyOrderDetailFeignService;
    private final SalesOrderDetailFeignService salesOrderDetailFeignService;
    private final BuyerFeignService buyerFeignService;

    /**
     * 查询租户的平台商家
     *
     * @return
     */
    @Cacheable(value = ScmCacheNameConstant.MANAGE_PLATFORM_MERCHANT, key = "0")
    public Merchant fetchPlatformMerchant() {
        R<Merchant> r = merchantFeignService.fetchPlatformMerchant(SecurityConstants.FROM_IN);
        if (RUtil.isFailed(r)) {
            throw new ErrorDataException("查询租户的平台商家失败");
        } else if (null == r.getData()) {
            throw new ErrorDataException("查询平台商家失败");
        }
        return r.getData();
    }

    /**
     * 获取店铺
     *
     * @param shopId
     * @return
     */
    public Shop fetchShopById(String shopId) {
        R<Shop> r = shopFeignService.getById(shopId, SecurityConstants.FROM_IN);
        if (RUtil.isFailed(r)) {
            throw new ErrorDataException("获取店铺失败");
        }
        return r.getData();
    }

    /**
     * 平台商家默认店铺(pds)
     *
     * @return
     */
    public ShopExtDTO fetchDefaultShop() {
        R<ShopExtDTO> r = shopFeignService.fetchDefaultShop(SecurityConstants.FROM_IN);
        if (RUtil.isFailed(r)) {
            throw new ErrorDataException("获取平台商家默认店铺失败:" + r.getMsg());
        }
        if (null == r.getData()) {
            throw new EmptyDataException("获取平台商家默认店铺失败: 无默认店铺");
        }
        return r.getData();
    }

    /**
     * 查询图片组图片
     *
     * @param groupNum
     * @return
     */
    public PhotoGroupDTO fetchPhotoGroup(String groupNum) {
        R<PhotoGroupDTO> r = photoGroupManageFeignService.fetchByGroupNum(groupNum, SecurityConstants.FROM_IN);
        if (RUtil.isFailed(r)) {
            throw new ErrorDataException("查询图片组图片失败");
        }
        return r.getData();
    }

    /**
     * 查询图片组图片列表
     *
     * @param groupNum
     * @return 找不到时 返回 空列表
     */
    @Cacheable(value = ScmCacheNameConstant.PHOTO_GROUP_LIST, key = "#groupNum", condition = "#groupNum != null")
    public List<PhotoGallery> fetchPhotoList(String groupNum) {
        List<PhotoGallery> photoList = new ArrayList<>(10);
        if (StrUtil.isNotBlank(groupNum)) {
            PhotoGroupDTO photoGroupDTO = fetchPhotoGroup(groupNum);
            if (null != photoGroupDTO) {
                photoList = photoGroupDTO.getPhotoList();
            }
        }
        return photoList;
    }

    /**
     * 保存或修改图片组图片
     * 修改时：需groupNum / photoList
     * 新增时 需 图片组名称/ 类别标签 / merchantId
     *
     * @param photoGroupDTO
     * @return
     */
    @CacheEvict(value = ScmCacheNameConstant.PHOTO_GROUP_LIST, key = "#photoGroupDTO.groupNum", condition = "#photoGroupDTO.groupNum != null")
    public String savePhotoGroup(PhotoGroupDTO photoGroupDTO) {
        R<PhotoGroupManage> r = photoGroupManageFeignService.savePhotoGroup(photoGroupDTO, SecurityConstants.FROM_IN);
        if (RUtil.isFailed(r)) {
            throw new ErrorDataException("保存或修改图片组图片失败");
        } else if (null == r.getData()) {
            return null;
        }
        return r.getData().getGroupNum();
    }

    public int countBuyOrderBuyGoods(Set<String> modelIdSet) {
        BuyOrderDetailReq req = new BuyOrderDetailReq();
        req.setModeIdSet(modelIdSet);
        R<Integer> r = buyOrderDetailFeignService.countByBuyOrderDetailReq(req, SecurityConstants.FROM_IN);
        if (RUtil.isFailed(r) || r.getData() == null) {
            throw new ErrorDataException("查询采购订单的商品规格数时失败");
        }
        return r.getData();
    }

    public int countSupplyOrderBuyGoods(Set<String> modelIdSet) {
        SupplyOrderDetailReq req = new SupplyOrderDetailReq();
        req.setModeIdSet(modelIdSet);
        R<Integer> r = supplyOrderDetailFeignService.countBySupplyOrderDetailReq(req, SecurityConstants.FROM_IN);
        if (RUtil.isFailed(r) || r.getData() == null) {
            throw new ErrorDataException("查询供应订单的商品规格数时失败");
        }
        return r.getData();
    }

    public int countSalesOrderBuyGoods(Set<String> modelIdSet) {
        SalesOrderDetailReq req = new SalesOrderDetailReq();
        req.setModeIdSet(modelIdSet);
        R<Integer> r = salesOrderDetailFeignService.countBySalesOrderDetailReq(req, SecurityConstants.FROM_IN);
        if (RUtil.isFailed(r) || r.getData() == null) {
            throw new ErrorDataException("查询销售订单的商品规格数时失败");
        }
        return r.getData();
    }

    /**
     * 平台定价的商家
     *
     * @param buyerId
     * @return
     */
    public String fetchBuyerMerchantId(String buyerId) {
        R<Buyer> r = buyerFeignService.getById(buyerId, SecurityConstants.FROM_IN);
        if (RUtil.isFailed(r)) {
            throw new ErrorDataException("查询供应订单的商品规格数时失败");
        }
        if (null == r.getData()) {
            return null;
        }
        return r.getData().getMerchantId();
    }

    /**
     * 平台定价的商家
     * 根据buyerId 找不到时使用平台商家
     *
     * @param pricingMerchantId 平台定价的商家id
     * @param buyerId           为空时使用平台商家
     * @return
     */
    @Cacheable(value = ScmCacheNameConstant.MANAGE_PRICING_MERCHANT_ID, key = "#pricingMerchantId +':'+ #buyerId")
    public String fetchPricingMerchantId(String pricingMerchantId, String buyerId) {
        if (StrUtil.isNotEmpty(pricingMerchantId)) {
            return pricingMerchantId;
        }
        String merchantId = StrUtil.isEmpty(buyerId) ? null : fetchBuyerMerchantId(buyerId);
        if (StrUtil.isEmpty(merchantId)) {
            merchantId = fetchPlatformMerchant().getId();
        }
        return merchantId;
    }

    /**
     * 定价的平台商家id
     *
     * @param shopId
     * @return
     */
    @Cacheable(value = ScmCacheNameConstant.MANAGE_PRICING_PM_ID, key = "#shopId")
    public String fetchPricingPmId(String shopId) {
        // 店铺商家，默认平台商家
        Shop shop = fetchShopById(shopId);
        return null == shop ? fetchPlatformMerchant().getId() : shop.getMerchantId();
    }

    public boolean salecGoodsMarketableChange(String goodsId, boolean marketable) {
        R<Boolean> r = storeProductFeignService.marketableChange(new StoreProductFeignReq(goodsId, marketable), SecurityConstants.FROM_IN);
        if (RUtil.isFailed(r) || r.getData() == null) {
            return false;
        }
        return r.getData();
    }

    /**
     * 删除商品的供应关联关系
     *
     * @param goodsId
     * @return
     */
    public boolean deleteSupplyRelation(String goodsId) {
        SupplierGoodsReq req = new SupplierGoodsReq();
        req.setGoodsId(goodsId);
        R<Boolean> r = supplierGoodsFeignService.deleteRelationByGoods(req, SecurityConstants.FROM_IN);
        if (RUtil.isFailed(r) || r.getData() == null) {
            return false;
        }
        return r.getData();
    }
}
